package com.education.user.service;

import com.education.common.utils.NumberUtils;
import com.education.common.utils.Token;
import com.education.user.api.UserApi;
import com.education.user.mapper.SysInfoMsgMapper;
import com.education.user.mapper.UserMapper;
import com.education.user.pojo.LoginAttempts;
import com.education.user.pojo.SysUserRole;
import com.education.user.pojo.User;
import com.education.user.utils.CodecUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: ly
 * @create: 2018-07-05 15:55
 **/
@Service
public class UserService implements UserApi {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SysUserRoleServiceImpl userRoleService;

    @Autowired
    private LoginAttemptsService loginAttemptsService;

    @Autowired
    private SysAppUserService sysAppUserService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SysInfoMsgMapper sysInfoMsgMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    private static final String KEY_PREFIX = "user:code:phone:";

    public Boolean checkData(String data, Integer type) {
        User t = new User();

        switch (type) {
            case 1:
                t.setSysPhone(data);
                break;
            //case 2:
            //    t.setPhone(data);
            //    break;
            default:
                return null;
        }
        return this.userMapper.selectCount(t) == 0;
    }

    public void sendCode(String phone) {
        String key = KEY_PREFIX + phone;
        // 1、生成验证码
        String code = NumberUtils.generateCode(6);
        // 2、存入redis
        this.redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
        // 3、发送消息
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        this.amqpTemplate.convertAndSend("ly.sms.exchange", "sms.verify.code", msg);
    }

    public boolean register(User user, String code) {
        String key = KEY_PREFIX + user.getSysPhone();
        // 先对验证码校验
        String cacheCode = this.redisTemplate.opsForValue().get(key);
        if (!StringUtils.equals(code, cacheCode)) {
            // 验证码有误
            return false;
        }
        // 完善数据
        user.setId(null);
        user.setCreateTime(new Date());

        // 生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);

        // 对密码加密
        user.setSysPassword(CodecUtils.md5Hex(user.getSysPassword(), salt));

        // 保存
        int count = this.userMapper.insert(user);

        return count == 1;
    }

    //@Override
    //public TStudent judgeStudent(String phone) {
    //    return sysInfoMsgMapper.judgeStudent(phone);
    //}

    @Override
    public User queryUserByUsernameAndPassword(String username, String password) {
        // 校验用户名
        User t = new User();
        t.setSysPhone(username);
        t.setSysState(0);
        User user = this.userMapper.selectOne(t);

        LoginAttempts loginAttempts = loginAttemptsService.queryByPhone(username);

        //给数据添加角色id
        if (user != null) {
            /*//登录次数限制表如果没有就添加
            if (loginAttempts == null) {
                LoginAttempts loginAttempts1 = new LoginAttempts();
                loginAttempts1.setSysPhone(username);
                loginAttempts1.setAttempts(0);
                loginAttempts1.setLastAttempt(new Date());
                loginAttemptsService.insert(loginAttempts1);
            }*/
            List<SysUserRole> sysUserRoles = userRoleService.selectSysByUserId(user.getId().intValue());
            if (sysUserRoles != null && sysUserRoles.size() > 0) {
                user.setRoleId(sysUserRoles.get(0).getRoleId());
            }
        }

        // 判断用户
        if (user == null) {
            return null;
        }
        // 判断密码是否正确
        if (!user.getSysPassword().equals(Token.getMD5String(password))) {

            //如果账号密码不正确，就将登录次数累加
            loginAttempts.setAttempts(loginAttempts.getAttempts() + 1);
            loginAttempts.setLastAttempt(new Date());
            loginAttemptsService.update(loginAttempts);

            return null;
        } else {

            //正确就将失败登陆次数归零
            loginAttempts.setAttempts(0);
            loginAttemptsService.update(loginAttempts);

        }
        /*if (!StringUtils.equals(user.getSysPassword(), CodecUtils.md5Hex(password, user.getSalt()))) {
            return null;
        }*/
        return user;
    }

    @Override
    public User queryUserByUsernameAndPassword2(String username, String password) {
        // 校验用户名
        User user = new User();
        user.setSysPhone(username);
        List<User> users = this.userMapper.select(user);
        // 判断用户
        if (users.size() == 0) {
            return null;
        }
        try {
            // 判断密码是否正确
            if (users.get(0).getSysPassword().equals(password)) {
                List<SysUserRole> sysUserRoles = userRoleService.selectSysByUserId(users.get(0).getId().intValue());
                if (sysUserRoles != null && sysUserRoles.size() > 0) {
                    users.get(0).setRoleId(sysUserRoles.get(0).getRoleId());
                }
                return users.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public boolean extisUser(String sysPhone) {
        User t = new User();
        t.setSysPhone(sysPhone);
        User user = this.userMapper.selectOne(t);
        return user != null;
    }


    public boolean satisfyLogin(User user) {
        String sysPhone = user.getSysPhone();
        user.setSysPassword(null);
        User user1 = this.userMapper.selectOne(user);
        LoginAttempts loginAttempts = loginAttemptsService.queryByPhone(sysPhone);
        if (loginAttempts == null) {
            LoginAttempts loginAttempts1 = new LoginAttempts();
            loginAttempts1.setSysPhone(sysPhone);
            loginAttempts1.setAttempts(0);
            loginAttempts1.setLastAttempt(new Date());
            loginAttemptsService.insert(loginAttempts1);
            return true;
        }
        //不是第一次登陆
        Integer attempts = loginAttempts.getAttempts();
        //最后一次登录时间
        long time = loginAttempts.getLastAttempt().getTime();
        long xz = System.currentTimeMillis();

        //如果当前登录次数小于就返回
        if (attempts < user1.getLogins()){
            return true;
        }

        return xz - time > 300000;

    }

    @GetMapping("query1")
    @Override
    public User queryUserByUsernameAndPassword1(String username, String password) {
        // 校验用户名
        User t = new User();
        t.setSysPhone(username);
        t.setSysState(0);
        User user = this.userMapper.selectOne(t);
        // 判断用户
        if (user == null) {
            return null;
        }
        try {
            // 判断密码是否正确
            if (user.getSysPassword().equals(Token.getMD5String(password))) {
//                user.setSysPhone(null);
                user.setSysPassword(null);
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {

        // String md5String = Token.getMD5String("123456");
        //System.out.println(md5String);
//        System.out.println(CodecUtils.md5Hex("123456", "05b0f203987e49d2b72b20b95e0e57d9"));
    }

    /**
     * 根据id查询信息
     *
     * @param userId
     * @return
     */
    public User selectSysUserById(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        return user;
    }

    //根据手机号查询该用户
    public List<User> findByPhone(String phone) {
        User user = new User();
        user.setSysPhone(phone);
        List<User> users = userMapper.select(user);
        return users;
    }

    //忘记密码
    public void updateByPhone(User user) {
        Example example = new Example(User.class);
        // where 条件
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("user", user);
        userMapper.updateByExampleSelective(user, example);
    }

    //修改密码
    public void updatePasswordByPhone(User user) {
        Example example = new Example(User.class);
        // where 条件
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", user.getId());
        criteria.andEqualTo("sysPassword", user.getSysPassword());
        userMapper.updateByExampleSelective(user, example);
    }

    /**
     * 修改角色
     *
     * @param user 角色信息
     * @return 结果
     */
    public int updateSysPassword(User user) {
        User user1 = new User();
        //id
        if (user.getId() != null) {
            user1.setId(user.getId());
        }
        //角色名称
        if (user.getSysPassword() != null) {
            user1.setSysPassword(user.getSysPassword());
        }
        return userMapper.updateByPrimaryKeySelective(user1);
    }


    //根据主键查询
    public User selectByPrimaryKey(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    //条件查询用户信息
    public List<User> select(User user) {
        return userMapper.select(user);
    }

    //添加用户信息
    public void insert(User user) {
        userMapper.insert(user);
    }

    //根据主键修改用户信息
    public Integer update(User user) {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("id", user.getId());
        return userMapper.updateByExampleSelective(user, example);
    }

    /**
     * 进行关联查询 学校名 和 班级名
     */
    public List<User> selectAppUserList(User user) {
        return userMapper.selectAppUserList(user);
    }

    /**
     * 查详情以及进行关联
     */
    public User selectOneAppUser(User user) {
        return userMapper.selectOneAppUser(user);
    }

    /**
     * 删除用户
     */
    public int deleteById(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    public Integer selectUserIdBySchoolId(int schoolId) {
        return userMapper.selectUserIdBySchoolId(schoolId);
    }
}
